Skip to main content
Version: 1.0.16

PREPARE TRANSACTION

PREPARE TRANSACTION — Prepare the current transaction for two-phase commit

Synopsis

PREPARE TRANSACTION transaction_id

Description

PREPARE TRANSACTION prepares the current transaction for two-phase commit. After this command, the transaction is no longer associated with the current session. Instead, its state is fully stored on disk, and there is a high probability that it will be committed successfully (even if a database crash occurs before the commit is requested).

Once prepared, the transaction can later be committed or rolled back using COMMIT PREPARED or ROLLBACK PREPARED, respectively. These commands can be issued from any session, not just the one that executed the original transaction.

From the perspective of the session that issued the command, PREPARE TRANSACTION is not unlike the ROLLBACK command: after executing it, there is no active current transaction, and the effects of the prepared transaction are no longer visible (if the transaction is committed, the effects will become visible again).

If the PREPARE TRANSACTION command fails for any reason, it becomes a ROLLBACK: the current transaction is canceled.

Parameters

transaction_id

An arbitrary transaction identifier that will later be used by COMMIT PREPARED or ROLLBACK PREPARED to identify this transaction. The identifier must be written as a string and must be less than 200 bytes in length. It must also not be the same as the identifier of any currently prepared transaction.

Notes

PREPARE TRANSACTION is not designed for use in applications or interactive sessions. Its purpose is to allow an external transaction manager to perform atomic global transactions across multiple databases or other transactional resources. Unless you are writing a transaction manager, you probably will not need to use PREPARE TRANSACTION.

This command must be used within a transaction block. The transaction block is started with BEGIN.

Currently, PREPARE is not allowed in a transaction that has executed any operations involving temporary tables or the session's temporary namespace, created cursors WITH HOLD, or executed LISTEN, UNLISTEN, or NOTIFY. These features are too tightly bound to the current session to be of any use for a prepared transaction.

If any runtime parameters of the transaction have been modified using SET (without the LOCAL option), these effects will persist after PREPARE TRANSACTION and will not be affected by any subsequent COMMIT PREPARED or ROLLBACK PREPARED. In this respect, therefore, PREPARE TRANSACTION behaves more like COMMIT than ROLLBACK.

All currently available prepared transactions are listed in the pg_prepared_xacts system view.

Examples

-- Prepare the current transaction for two-phase commit, using foobar as the transaction identifier:

PREPARE TRANSACTION 'foobar';

See Also

COMMIT PREPARED, ROLLBACK PREPARED